<template>
  <div class="min-h-screen bg-gradient-to-br from-emerald-50 to-teal-50 flex flex-col">



    <!-- 主内容区 -->
    <main class="flex-1 flex items-center justify-center px-4 sm:px-6 lg:px-8 py-12">
      <div class="w-full max-w-md">
        <!-- 卡片容器 -->
        <div class="bg-white rounded-lg shadow-xl overflow-hidden transition-all duration-500 transform hover:shadow-2xl">
          <!-- 标题栏 -->
          <div class="bg-emerald-600 p-6">
            <h2 class="text-center text-white text-2xl font-bold">
              {{ isLoginMode ? '账户登录' : '注册新账户' }}
            </h2>
            <p class="text-center text-emerald-100 mt-1">
              {{ isLoginMode ? '请输入您的账户信息' : '创建您的账户以开始使用' }}
            </p>
          </div>

          <!-- 表单区域 -->
          <div class="p-6">
            <form @submit.prevent="handleSubmit">
              <!-- 注册模式额外显示的字段 -->
              <div v-if="!isLoginMode" class="mb-4">
                <label for="name" class="block text-sm font-medium text-gray-700 mb-1">
                  姓名
                </label>
                <div class="relative">
                  <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <i class="fa fa-user text-gray-400"></i>
                  </div>
                  <input
                      id="name"
                      v-model="formData.name"
                      type="text"
                      class="pl-10 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-emerald-500 focus:border-emerald-500 transition-colors"
                      placeholder="请输入您的姓名"
                  >
                </div>
                <p v-if="errors.name" class="mt-1 text-sm text-red-600">{{ errors.name }}</p>
              </div>

              <!-- 邮箱字段 -->
              <div class="mb-4">
                <label for="email" class="block text-sm font-medium text-gray-700 mb-1">
                  邮箱地址
                </label>
                <div class="relative">
                  <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <i class="fa fa-envelope text-gray-400"></i>
                  </div>
                  <input
                      id="email"
                      v-model="formData.email"
                      type="email"
                      class="pl-10 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-emerald-500 focus:border-emerald-500 transition-colors"
                      placeholder="your@email.com"
                  >
                </div>
                <p v-if="errors.email" class="mt-1 text-sm text-red-600">{{ errors.email }}</p>
              </div>

              <!-- 密码字段 -->
              <div class="mb-4">
                <label for="password" class="block text-sm font-medium text-gray-700 mb-1">
                  密码
                </label>
                <div class="relative">
                  <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <i class="fa fa-lock text-gray-400"></i>
                  </div>
                  <input
                      id="password"
                      v-model="formData.password"
                      :type="showPassword ? 'text' : 'password'"
                      class="pl-10 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-emerald-500 focus:border-emerald-500 transition-colors"
                      placeholder="请输入密码"
                  >
                  <button
                      type="button"
                      @click="showPassword = !showPassword"
                      class="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-gray-600"
                  >
                    <i :class="showPassword ? 'fa fa-eye-slash' : 'fa fa-eye'"></i>
                  </button>
                </div>
                <p v-if="errors.password" class="mt-1 text-sm text-red-600">{{ errors.password }}</p>
              </div>

              <!-- 注册模式确认密码字段 -->
              <div v-if="!isLoginMode" class="mb-6">
                <label for="confirmPassword" class="block text-sm font-medium text-gray-700 mb-1">
                  确认密码
                </label>
                <div class="relative">
                  <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <i class="fa fa-lock text-gray-400"></i>
                  </div>
                  <input
                      id="confirmPassword"
                      v-model="formData.confirmPassword"
                      :type="showPassword ? 'text' : 'password'"
                      class="pl-10 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-emerald-500 focus:border-emerald-500 transition-colors"
                      placeholder="请再次输入密码"
                  >
                </div>
                <p v-if="errors.confirmPassword" class="mt-1 text-sm text-red-600">{{ errors.confirmPassword }}</p>
              </div>

              <!-- 登录模式记住我选项 -->
              <div v-if="isLoginMode" class="flex items-center mb-6">
                <input
                    id="remember-me"
                    v-model="formData.rememberMe"
                    type="checkbox"
                    class="h-4 w-4 text-emerald-600 focus:ring-emerald-500 border-gray-300 rounded"
                >
                <label for="remember-me" class="ml-2 block text-sm text-gray-700">
                  记住我
                </label>
              </div>

              <!-- 提交按钮 -->
              <button
                  type="submit"
                  :disabled="isLoading"
                  class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-emerald-600 hover:bg-emerald-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-emerald-500 transition-colors disabled:opacity-70 disabled:cursor-not-allowed"
              >
                <i v-if="isLoading" class="fa fa-spinner fa-spin mr-2"></i>
                {{ isLoginMode ? '登录' : '注册' }}
              </button>

              <!-- 错误提示 -->
              <p v-if="errorMessage" class="mt-4 text-center text-sm text-red-600">{{ errorMessage }}</p>

              <!-- 切换模式链接 -->
              <div class="mt-6 text-center">
                <button
                    type="button"
                    @click="toggleMode"
                    class="font-medium text-emerald-600 hover:text-emerald-500 focus:outline-none transition-colors"
                >
                  {{ isLoginMode ? '还没有账户？立即注册' : '已有账户？立即登录' }}
                </button>
              </div>

              <!-- 忘记密码链接 -->
              <div v-if="isLoginMode" class="mt-4 text-center">
                <a
                    href="#"
                    class="text-sm text-gray-600 hover:text-emerald-600 focus:outline-none transition-colors"
                >
                  忘记密码？
                </a>
              </div>
            </form>
          </div>
        </div>

        <!-- 底部说明 -->
        <p class="mt-6 text-center text-sm text-gray-500">
          &copy; 2025 碳积分管理平台. 保留所有权利.
        </p>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';

// 路由实例
const router = useRouter();

// 状态管理
const isLoginMode = ref(true); // 登录/注册模式切换
const showPassword = ref(false); // 密码显示切换
const isLoading = ref(false); // 提交加载状态

// 表单数据
const formData = ref({
  name: '',
  email: '',
  password: '',
  confirmPassword: '',
  rememberMe: false
});

// 错误信息
const errors = ref({});
const errorMessage = ref('');

// 切换登录/注册模式
const toggleMode = () => {
  // 切换模式时重置表单和错误信息
  isLoginMode.value = !isLoginMode.value;
  resetForm();
};

// 重置表单
const resetForm = () => {
  formData.value = {
    name: '',
    email: '',
    password: '',
    confirmPassword: '',
    rememberMe: false
  };
  errors.value = {};
  errorMessage.value = '';
};

// 表单验证
const validateForm = () => {
  const newErrors = {};
  let isValid = true;

  // 邮箱验证
  if (!formData.value.email) {
    newErrors.email = '请输入邮箱地址';
    isValid = false;
  } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.value.email)) {
    newErrors.email = '请输入有效的邮箱地址';
    isValid = false;
  }

  // 密码验证
  if (!formData.value.password) {
    newErrors.password = '请输入密码';
    isValid = false;
  } else if (formData.value.password.length < 6) {
    newErrors.password = '密码长度不能少于6位';
    isValid = false;
  }

  // 注册模式额外验证
  if (!isLoginMode.value) {
    // 姓名验证
    if (!formData.value.name) {
      newErrors.name = '请输入您的姓名';
      isValid = false;
    }

    // 确认密码验证
    if (!formData.value.confirmPassword) {
      newErrors.confirmPassword = '请确认密码';
      isValid = false;
    } else if (formData.value.password !== formData.value.confirmPassword) {
      newErrors.confirmPassword = '两次输入的密码不一致';
      isValid = false;
    }
  }

  errors.value = newErrors;
  return isValid;
};

// 处理表单提交
// 处理表单提交（修改后的前端模拟版本）
const handleSubmit = async () => {
  // 验证表单
  if (!validateForm()) {
    return;
  }

  // 显示加载状态
  isLoading.value = true;
  errorMessage.value = '';

  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 1000));

    // 【核心修改】前端预设的测试账号（模拟数据库）
    const testUser = {
      email: 'admin@example.com',
      password: '123456', // 测试密码
      name: '管理员',
      role: '系统管理员',
      avatar: 'https://picsum.photos/id/1005/200/200'
    };

    if (isLoginMode.value) {
      // 登录逻辑：验证输入是否与测试账号匹配
      if (
          formData.value.email === testUser.email &&
          formData.value.password === testUser.password
      ) {
        // 登录成功：保存用户信息到localStorage
        localStorage.setItem('currentUser', JSON.stringify(testUser));

        // 跳转到仪表盘
        router.push('/dashboard');
      } else {
        // 登录失败
        errorMessage.value = '邮箱或密码错误（测试账号：admin@example.com / 123456）';
      }
    } else {
      // 注册逻辑：前端直接保存新用户（模拟注册成功）
      const newUser = {
        email: formData.value.email,
        name: formData.value.name,
        role: '普通用户',
        avatar: 'https://picsum.photos/id/1012/200/200'
      };

      // 保存新用户到localStorage（实际项目中这里会调用后端API）
      localStorage.setItem('currentUser', JSON.stringify(newUser));

      // 注册成功后跳转到首页
      errorMessage.value = '注册成功，即将跳转到首页...';
      setTimeout(() => {
        router.push('/dashboard');
      }, 1500);
    }
  } catch (err) {
    errorMessage.value = '操作失败，请重试';
    console.error('错误:', err);
  } finally {
    isLoading.value = false;
  }
};
</script>

<style scoped>
/* 动画效果 */
input:focus, button:focus {
  transition: all 0.2s ease-in-out;
}

/* 输入框获得焦点时的动画 */
input:focus {
  transform: translateY(-1px);
}

/* 按钮悬停动画 */
button[type="submit"]:not(:disabled):hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 6px -1px rgba(52, 211, 153, 0.2);
}

button[type="submit"]:not(:disabled):active {
  transform: translateY(0);
}

/* 平滑过渡 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}
</style>
